package com.wxx;

/**
 * @author Jetwang
 * @version 1.0
 * @date 2022/4/17 21:48
 */
public class LinkedListQueue<T> implements Queue<T>{
    private Node head, tail;
    private int size;

    public LinkedListQueue() {
        tail = null;
        head = null;
        size = 0;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void enqueue(T t) {
        // 队列为空
        if (tail == null) {
            tail = new Node(t);
            head = tail;
        } else {
            tail.next = new Node(t);
            tail = tail.next;
        }
        size++;
    }

    @Override
    public T dequeue() {
        // 队列为空
        if (isEmpty()) {
            throw new IllegalArgumentException("Cannot dequeue from an empty queue");
        }
        Node retNode = head;
        head = head.next;
        retNode.next = null;
        if (head == null) {
            tail = null;
        }
        size--;
        return (T) retNode.t;
    }

    @Override
    public T getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Queue is empty");
        }
        return (T) head.t;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append("Queue: front ");
        Node cur = head;
        while (cur != null) {
            res.append(cur.t + "->");
            cur = cur.next;
        }
        res.append("null tail");
        return res.toString();
    }
}
